﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DSkin.Forms;
using DSkin.Controls;
using TY_Hoist.WinApp.Code;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;

namespace TY_Hoist.WinApp
{
    /// <summary>
    /// 主程序窗体
    /// </summary>
    public partial class MainForm : BaseForm
    {
        /// <summary>
        /// 实例化遥控器
        /// </summary>
        RemoteControl remoteControl;
        /// <summary>
        /// 实例化激光测距传感器
        /// </summary>
        LaserRanger laserRanger;
        bool autoUpDownSwich = false;
        bool processSwich = false;
        bool isAutoTop = false;
        bool isAutoBottom = false;
        Color processBtnBaseColor;
        double currentValue = 0;
        double laserRangerInitValue = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// //窗体加载完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {

                remoteControl = new RemoteControl();
                laserRanger = new LaserRanger();

            }
            catch (Exception ex)
            {

                DSkinMessageBox.Show(ex.Message);
            }
            processBtnBaseColor = BtnProcessSwich.BaseColor;
            FreeStatus();
            //timer首次计时到达前手动执行一次显示
            labDisplayTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH点mm分ss秒");
            //启动显示timer
            timer1.Start();

        }

        /// <summary>
        /// 时间显示事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            labDisplayTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH点mm分ss秒");
        }

        /// <summary>
        /// 遥控器上升开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTop_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCTop(true);
            LabStatus.Text = "正在上升...";
        }

        /// <summary>
        /// 遥控器上升关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTop_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCTop(false);
            FreeStatus();
        }

        /// <summary>
        /// 遥控器下降开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBottom_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCBottom(true);
            LabStatus.Text = "正在下降...";
        }

        /// <summary>
        /// 遥控器下降关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBottom_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCBottom(false);
            FreeStatus();
        }

        /// <summary>
        /// 遥控器前进开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCUp(true);
            LabStatus.Text = "正在向前移动...";
        }

        /// <summary>
        /// 遥控器前进关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCUp(false);
            FreeStatus();
        }

        /// <summary>
        /// 遥控器后退开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDown_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCDown(true);
            LabStatus.Text = "正在向后移动...";
        }

        /// <summary>
        /// 遥控器后退关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDown_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCDown(false);
            FreeStatus();
        }

        /// <summary>
        /// 遥控器左移开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnLeft_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCLeft(true);
            LabStatus.Text = "正在向左移动...";
        }

        /// <summary>
        /// 遥控器左移关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnLeft_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCLeft(false);
            FreeStatus();
        }


        /// <summary>
        /// 遥控器右移开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRIght_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCRight(true);
            LabStatus.Text = "正在向右移动...";
        }

        /// <summary>
        /// 遥控器右移关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRIght_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCRight(false);
            FreeStatus();
        }

        /// <summary>
        /// 遥控器启动开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRCStart_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCStart(true);
        }

        /// <summary>
        /// 遥控器启动关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRCStart_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCStart(false);
        }

        /// <summary>
        /// 遥控器停止开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRCStop_MouseDown(object sender, MouseEventArgs e)
        {
            remoteControl.RCStop(true);
        }

        /// <summary>
        /// 遥控器停止关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRCStop_MouseUp(object sender, MouseEventArgs e)
        {
            remoteControl.RCStop(false);
        }


        /// <summary>
        /// 自动升降系统UI控制
        /// </summary>
        /// <param name="swich"></param>
        private void AutoUpDownUIControl(bool swich)
        {

            if (!swich)
            {
                //停止自动上升
                remoteControl.RCTop(false);
                //停止自动下降
                remoteControl.RCBottom(false);
                numAutoValue.Value = 0;
                isAutoBottom = false;
                isAutoTop = false;
                panelRCDirection.Enabled = btnTop.Enabled = btnBottom.Enabled = true;
                //当流程为开始状态时执行
                if (processSwich)
                {
                    BtnAutoTop.Enabled = BtnAutoBottom.Enabled = numAutoValue.Enabled = true;
                    FreeStatus();
                }
            }
            else
            {

                panelRCDirection.Enabled = btnTop.Enabled = btnBottom.Enabled =
                BtnAutoTop.Enabled = BtnAutoBottom.Enabled = numAutoValue.Enabled = false;
            }
        }

        /// <summary>
        /// 流程开关UI控制
        /// </summary>
        /// <param name="swich"></param>
        private void ProcessSwichUIControl(bool swich)
        {
            BtnAutoTop.Enabled = BtnAutoBottom.Enabled = numAutoValue.Enabled = swich;
            FreeStatus();
            if (!swich)
            {
                this.labCurrentValue.Text = "0 cm";
                numAutoValue.Value = 0;
            }
        }

        /// <summary>
        /// 结束程序事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            remoteControl.Clear();
            //释放串口
            remoteControl.Dispose();

            laserRanger.Stop();
            laserRanger.Clear();
            laserRanger.Dispose();
        }

        private void BtnProcessSwich_Click(object sender, EventArgs e)
        {

            if (!processSwich)
            {
                if (DSkinMessageBox.Show(this, "开始流程前请确保物体离地面0cm，且刚好接触地面！", "提醒", MessageBoxIcon.Information, false, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Task.Factory.StartNew(() =>
                    {

                        this.Invoke(new Action(delegate
                        {
                            LabStatus.Text = "正在初始化激光测距...";

                        }));
                        laserRangerInitValue = laserRanger.GetStableValue();
                        this.Invoke(new Action(delegate
                        {
                            LabStatus.Text = "激光测距初始化成功.";

                        }));
                        this.Invoke(new Action(delegate
                        {
                            BtnProcessSwich.BaseColor = Color.Red;
                            BtnProcessSwich.Text = "结束";
                            processSwich = true;
                            ProcessSwichUIControl(true);
                        }));
                        int js = 0;
                        bool dd = false;
                        while (processSwich)
                        {

                            this.BeginInvoke(new Action(delegate
                            {
                                js++;
                                var val = laserRanger.GetValue();
                                if (val != -1)
                                {
                                    var oldValue = currentValue;
                                    currentValue = laserRangerInitValue - val;


                                    if (isAutoTop || isAutoBottom)
                                    {
                                        var zhi = isAutoTop ? currentValue - oldValue : oldValue - currentValue;
                                        if (js >= 20 && Convert.ToDouble(this.numAutoValue.Value) - zhi <= 15)
                                        {
                                            js = 0;
                                            if (isAutoTop)
                                            {
                                                //停止自动上升
                                                remoteControl.RCTop(false);

                                            }
                                            else
                                            {
                                                //停止自动下降
                                                remoteControl.RCBottom(false);
                                            }
                                        }
                                        if (zhi < 0 && dd == false)
                                        {

                                            if (Convert.ToDouble(this.numAutoValue.Value) - zhi > 3)
                                            {
                                                dd = true;
                                                Task.Factory.StartNew(() =>
                                                {

                                                    if (isAutoTop)
                                                    {

                                                        remoteControl.RCTop(true);
                                                        Thread.Sleep(600);
                                                        remoteControl.RCTop(false);

                                                    }
                                                    else
                                                    {
                                                        remoteControl.RCBottom(true);
                                                        Thread.Sleep(600);
                                                        remoteControl.RCBottom(false);
                                                    }
                                                    dd = false;
                                                });

                                            }
                                            if (Convert.ToDouble(this.numAutoValue.Value) - zhi < -3)
                                            {
                                                dd = true;
                                                Task.Factory.StartNew(() =>
                                                {
                                                    if (isAutoTop)
                                                    {
                                                        remoteControl.RCBottom(true);
                                                        Thread.Sleep(600);
                                                        remoteControl.RCBottom(false);

                                                    }
                                                    else
                                                    {
                                                        remoteControl.RCTop(true);
                                                        Thread.Sleep(600);
                                                        remoteControl.RCTop(false);
                                                    }
                                                    dd = false;
                                                });

                                            }
                                        }
                                        if (dd = false && zhi < 0)
                                        {
                                            this.numAutoValue.Value = 0;
                                            AutoUpDownUIControl(false);
                                        }
                                        else
                                        {
                                            this.numAutoValue.Value = Convert.ToInt32(this.numAutoValue.Value - Convert.ToDecimal(zhi));
                                        }
                                    }

                                    labCurrentValue.Text = string.Format("{0} cm", Convert.ToInt32(currentValue));
                                }
                            }));
                            Thread.Sleep(100);
                        }
                        labCurrentValue.Text = "0 cm";
                        numAutoValue.Value = 0;
                    });
                }

            }
            else
            {
                if (DSkinMessageBox.Show(this, "确定要结束流程么？", "提醒", MessageBoxIcon.Information, false, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    BtnProcessSwich.BaseColor = processBtnBaseColor;
                    BtnProcessSwich.Text = "开始";
                    processSwich = false;
                    AutoUpDownUIControl(false);
                    ProcessSwichUIControl(false);
                }

            }
        }

        private void BtnAutoTop_Click(object sender, EventArgs e)
        {
            remoteControl.RCTop(true);
            AutoUpDownUIControl(true);
            LabStatus.Text = "正在自动上升...";
            isAutoTop = true;

        }

        private void BtnAutoBottom_Click(object sender, EventArgs e)
        {
            remoteControl.RCBottom(true);
            AutoUpDownUIControl(true);
            LabStatus.Text = "正在自动下降...";
            isAutoBottom = true;
        }

        private void BtnRCStop_Click(object sender, EventArgs e)
        {
            AutoUpDownUIControl(false);
        }

        private void BtnRCStart_Click(object sender, EventArgs e)
        {

        }

        private void FreeStatus()
        {
            if (processSwich)
            {
                LabStatus.Text = "流程为开启状态，等待操作...";
            }
            else
            {
                LabStatus.Text = "流程未开始（将物品移动至接触地面后开始流程）";
            }
        }

        private void BtnCloseForm_Click(object sender, EventArgs e)
        {

            if (processSwich)
            {
                DSkinMessageBox.Show("关闭系统前请先结束实验流程！");
            }
            else
            {
                if (DSkinMessageBox.Show(this, "确定要关闭系统么？", "提醒", MessageBoxIcon.Information, false, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //remoteControl.Clear();
                    ////释放串口
                    //remoteControl.Dispose();

                    //laserRanger.Stop();
                    //laserRanger.Clear();
                    //laserRanger.Dispose();

                    System.Diagnostics.Process.Start("shutdown.exe", "-s -t 0");
                }
            }
        }

        private void btnTop_Click(object sender, EventArgs e)
        {

        }

        private void btnUp_Click(object sender, EventArgs e)
        {

        }

        private void BtnLeft_Click(object sender, EventArgs e)
        {

        }

        private void BtnRIght_Click(object sender, EventArgs e)
        {

        }
    }
}
